package com.alavente.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.alavente.adapters.ClientAdapter;
import com.alavente.forms.ClientForm;
import com.alavente.objects.Client;
import com.alavente.service.ClientManager;

public class ClientAction extends DispatchAction {

	public ActionForward create(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		ClientForm f = (ClientForm)form;
		Client client = new Client();
		
		new ClientAdapter().adapt(f, client);
		
		client = new ClientManager().createClient(client);
			
		if (client != null) {					
			request.getSession().setAttribute("isAuthenticated", true);
			request.getSession().setAttribute("client", client);
			return mapping.findForward("success"); 
		}
		else {
			return mapping.findForward("failure"); 
		}
	}
	
	public ActionForward update(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		ClientForm f = (ClientForm)form;
		Client client = new Client();
		
		new ClientAdapter().adapt(f, client);
		
		client = new ClientManager().updateClient(client);
			
		if (client != null) {					
			request.getSession().setAttribute("isAuthenticated", true);
			request.getSession().setAttribute("client", client);
			return mapping.findForward("success"); 
		}
		else {
			return mapping.findForward("failure"); 
		}
	}
}
